import { loginApi, userInfoApi, userInById } from '@/api/user.js'
import { setToken, getToken, removeToken, setTimeLogin } from '@/utils/auth'
export default {
  namespaced: true,
  state: {
    token: getToken(),
    user: {}
  },
  mutations: {
    setToken(state, token) {
      state.token = token
    },
    userInfo(state, username) {
      state.user = username
    },
    // 清除token
    removeToken(state) {
      state.token = null
      removeToken()
    },
    // 清除用户信息
    removeUseInfo(state) {
      state.user = {}
    }

  },
  actions: {
    // 退出登录
    logout(ctx) {
      ctx.commit('removeToken')
      ctx.commit('removeUseInfo')
    },
    // 用户信息
    async  userInfo(ctx) {
      const res = await userInfoApi()
      const res1 = await userInById(res.userId)
      console.log(res, res1)
      ctx.commit('userInfo', { ...res, ...res1 })
    },

    // 登录
    async login(ctx, data) {
      const res = await loginApi(data)
      console.log(res)
      ctx.commit('setToken', res)
      setToken(res)
      setTimeLogin()
    }
  }

}
